package com.lehecai.core.task.sender;

import com.lehecai.core.task.IAsyncTask;
import com.lehecai.core.task.entity.AsyncTaskItem;
import com.lehecai.core.task.sender.validator.IAsyncTaskSenderValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by qatang on 14-3-26.
 */
public abstract class AbstractAsyncTaskSender implements IAsyncTaskSender {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private IAsyncTaskSenderValidator asyncTaskSenderValidator;

    @Override
    public AsyncTaskItem send(IAsyncTask asyncTask) throws Exception {
        if (asyncTask == null) {
            throw new Exception("发送单一异步任务失败：asyncTask参数对象不能为空");
        }

        if (asyncTaskSenderValidator != null) {
            if (!asyncTaskSenderValidator.validate(asyncTask)) {
                return null;
            }
        }

        AsyncTaskItem asyncTaskItem = createTaskData(asyncTask);
        if (asyncTaskItem == null || asyncTaskItem.getId() == null) {
            throw new Exception("发送单一异步任务失败：创建异步任务数据失败，请确认数据库是否正确");
        }

        executeSend(asyncTaskItem);

        return asyncTaskItem;
    }

    /**
     * 执行发送任务
     * @param asyncTaskItem
     */
    protected abstract void executeSend(AsyncTaskItem asyncTaskItem);

    /**
     * 创建异步任务数据保存至数据库，返回保存对象
     * @param asyncTask
     */
    protected abstract AsyncTaskItem createTaskData(IAsyncTask asyncTask) throws Exception;

    public IAsyncTaskSenderValidator getAsyncTaskSenderValidator() {
        return asyncTaskSenderValidator;
    }

    public void setAsyncTaskSenderValidator(IAsyncTaskSenderValidator asyncTaskSenderValidator) {
        this.asyncTaskSenderValidator = asyncTaskSenderValidator;
    }
}
